package com.alipay.rebate.shop.configuration.shiro.realm;

import com.alipay.rebate.shop.constants.StatusCode;
import com.alipay.rebate.shop.constants.UserContant;
import com.alipay.rebate.shop.exceptoin.AuthUserNameNotRightException;
import com.alipay.rebate.shop.exceptoin.BusinessException;
import com.alipay.rebate.shop.pojo.user.customer.UserDto;
import com.alipay.rebate.shop.service.customer.CustomerUserService;
import com.alipay.rebate.shop.utils.EncryptUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UserNamePasswordRealm extends AuthorizingRealm {

    private final Logger logger = LoggerFactory.getLogger(UserNamePasswordRealm.class);

    private CustomerUserService userService;

    public UserNamePasswordRealm(CustomerUserService userService) {
        this.userService = userService;
        this.setCredentialsMatcher(new HashedCredentialsMatcher(Sha256Hash.ALGORITHM_NAME));
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        logger.debug("Get into UserNamePasswordRealm");
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)token;
        logger.debug("UsernamePasswordToken is :{}",usernamePasswordToken);
        String userName = usernamePasswordToken.getUsername();
        logger.debug("userName is :{}",userName);
        char[] password = usernamePasswordToken.getPassword();
        logger.debug("password is: {}",password);
        // get from database
        UserDto user = userService.getUserDtoInfoForUserNamePasswordLogin(userName);
        if(user == null){
            throw new AuthUserNameNotRightException();
        }
        if(UserContant.USER_STATUS_BLACK.equals(user.getUserStatus())){
            throw new BusinessException(StatusCode.USER_IN_BLACK_LIST);
        }
        if(UserContant.USER_STATUS_LOGOFF.equals(user.getUserStatus())){
            throw new BusinessException("账号不存在",StatusCode.INTERNAL_ERROR);
        }
        logger.debug("UserDto is: {}",user);
        return new SimpleAuthenticationInfo(user, user.getEncryptPwd(), ByteSource.Util.bytes(
            EncryptUtil.encryptSalt), "dbRealm");
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
}
